package com.fastjrun.util.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import com.fastjrun.util.AbstractIPUtil;
import com.fastjrun.util.IpUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class IPUtilWithIP138 extends AbstractIPUtil implements IpUtil {

    @Override
    public String locateWanIP() {
        InputStream ins = null;
        String ip="127.0.0.1";
        try {
            URL url = new URL("https://202020.ip138.com/");
            URLConnection con = url.openConnection();
            ins = con.getInputStream();
            InputStreamReader isReader = new InputStreamReader(ins, "UTF-8");
            BufferedReader bReader = new BufferedReader(isReader);
            StringBuffer webContent = new StringBuffer();
            String str = null;
            while ((str = bReader.readLine()) != null) {
                webContent.append(str);
            }
            System.out.println("webContent:"+webContent);

            Document doc = Jsoup.parse(String.valueOf(webContent));//解析网页得到文档对象
            Elements elements = doc.getElementsByTag("title");//获取tag是title的所有dom文档
            Element element = elements.get(0);//获取第一个元素
            String title = element.text(); //.html是返回html
            System.out.println("网页标题："+title);
            ip=title.replace("您的IP地址是：","");
            System.out.println("ip："+ip);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ip;
    }

}
